# coding: utf-8
__author__ = 'zhaoyoucai'

from django import template

from aliexpress.models import *

import datetime,time

import hashlib

import json

import requests


import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )


register = template.Library()


def storeId2name(storeId):
    try:
        st = Store.objects.get(store_id=storeId)
        return st.seller
    except:
        return storeId

def calPrice(price,discount):
    if price:
        if discount:
            return round(price*(100-discount)/100,2)
        else:
            return price
    else:
        return 'None'


def getCompetitor(productId):
    p = Products.objects.get(product_id=productId)
    ids = Competitor.objects.filter(my_product=p).values('mo_product')
    competitor = Products.objects.filter(id__in=ids)
    html = ''
    for product in competitor:
        html += '<tr class="p-%s" style="background: #ccc;">'%(product.product_id)
        html += '<td class="sorting_1"><a href="javascript:;" class="link-compare"><label class="compare"><input type="checkbox" value="%s"><input type="hidden" name="compare-img" value="%s">对比</label></a><br><a href="/product/%s" target="_blank" class="preview" data-src="%s"><img data-src="%s" class="img-thumbnail" alt="" src="%s" data-holder-rendered="true" style="width: 60px; height: 60px;"></a></td>'%(product.product_id,product.thumb,product.product_id,product.thumb,product.thumb,product.thumb)
        if product.low_price == product.high_price:
            price = product.low_price*(100-product.discount)/100
            html += '<td class="price-%s">%s</td>'%(product.product_id,str(price))
        else:
            lowprice = product.low_price*(100-product.discount)/100
            highprice = product.high_price*(100-product.discount)/100
            html += '<td class="price-%s">%s <br>-<br> %s </td>'%(product.product_id,str(lowprice),str(highprice))
        html += '<td class="wish-%s">%d</td>'%(product.product_id,product.wish_list)
        html += '<td class="votes-%s">%d</td>'%(product.product_id,product.votes)
        html += '<td class="rating-%s">%s</td>'%(product.product_id,str(product.average_star_rating))
        #html += '<td class="feedback-%s">%d</td>'%(product.product_id,product.all_feedback)
        html += '<td class="sum-%s ">%d</td>'%(product.product_id,product.transactions_in_last_six_months)
        html += '<td class="order-%s">%d</td>'%(product.product_id,product.orders)
        if product.product_update_date:
            dtstr = str(product.product_update_date).split(' ')[0]
            tistr = str(product.product_update_date).split(' ')[1].split('.')[0]
        else:
            dtstr = ''
            tistr = ''
        html += '<td class="time-%s">%s<br>%s</td>'%(product.product_id,dtstr,tistr)
        html += '<td sta-%s><button id="s-%s" onclick="get_product(\'%s\')" class="btn btn-icon btn-purple m-b-4"><i class="zmdi zmdi-play-circle"></i></button><button id="s2-%s" onclick="get_transactions(\'%s\')" class="btn btn-icon btn-inverse m-b-4"><i class="zmdi zmdi-play-circle"></i></button></td>'%(product.product_id,product.product_id,product.product_id,product.product_id,product.product_id)
        html += '</tr>'

    return html


def Translate(word):
    result = ''
    app_id = '20161031000031072'
    app_key = '_OP9_QNAB5p1kKwVNx1X'
    salt = int(time.time())

    #拼接签名
    signstr ='%s%s%d%s'%(app_id,word,salt,app_key)
    m = hashlib.md5()
    m.update(signstr)
    sign = m.hexdigest()

    url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?q=%s&from=auto&to=zh&appid=%s&salt=%d&sign=%s'%(word,app_id,salt,sign)

    r = requests.get(url)
    data = r.content

    data = json.loads(data)

    result += data["trans_result"][0]["dst"]

    return result

#产品列表转换国家编码为中文
def TranslateCountry(country):
    result = ''
    if country:
        tmp = country.split(',')
        for item in tmp:
            try:
                c = Country.objects.get(country_code=item.upper())
                result += '%s(%s)'%(c.country_name_cn,c.country_code)
            except:
                result += item
            result +=','

    result = result.strip(',')
    return result

def TranslateProductTitle(productId):
    product = Products.objects.get(product_id=productId)
    title = product.product_title
    if product.product_title_chinese:
        title = product.product_title_chinese
    else:
        try:
            configure = Configure.objects.filter(key=u'启用翻译')
            if configure:
                value = configure[0].value
                if value == u'是':
                    title = Translate(product.product_title)
                    product.product_title_chinese = title
                    product.save()
                    #print('调用翻译接口，翻译字符数：%d'%(len(product.product_title)))
                else:
                    print(u'翻译未启用')
        except Exception as e:
            print(e)

    #title = product.product_title
    return title


def TranslateSearchWords(wordId):
    word = SearchWords.objects.get(pk=wordId)
    title = ''
    if word.keyword_chinese:
        title = word.keyword_chinese
    else:
        try:
            configure = Configure.objects.filter(key=u'启用翻译')
            if configure:
                value = configure[0].value
                if value == u'是':
                    title = Translate(word.keyword)
                    word.keyword_chinese = title
                    word.save()
                    #print('翻译字数：%d'%(len(word.keyword)))
                else:
                    print(u'翻译未启用')

        except Exception as e:
            print(e)
    #title = word.keyword
    return title

register.filter("storeId2name", storeId2name)
register.filter("calPrice", calPrice)
register.filter("getCompetitor", getCompetitor)
register.filter("TranslateProductTitle", TranslateProductTitle)
register.filter("TranslateSearchWords", TranslateSearchWords)
register.filter("TranslateCountry", TranslateCountry)
